package com.example.springboot_mvc_demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.springboot_mvc_demo.dto.ImRequest;
import com.example.springboot_mvc_demo.utils.OkHttpUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description:
 * <P> Date: 2024/7/16:10:21
 */

@SuppressWarnings({"unchecked", ""})
@Controller
@ResponseBody
@RequestMapping("/im")
public class ImController {
    private static final Logger log = LoggerFactory.getLogger(ImController.class);

    @PostMapping("/receive")
    public Map receive(@RequestBody ImRequest request) throws Exception {
        log.info("receiveParameters:{}", request);

        String message = sendMsg(request);

        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("data", message);
        return map;
    }

    /**
     * 构造参数 发送到对方接口
    */
    private String sendMsg(ImRequest request) throws Exception {
        Map<String, Object> toMap = buildMap(request);
        String result = OkHttpUtils.builder()
                .url("https://api.binjie.fun/api/generateStream?refer__1360=n4%2BxcDy7ezDtGODlxGrRDRiA7G%3DD8C%2FiKPD")
                .addHeader("Origin", "https://chat18.aichatos8.com")
                .addHeader("Referer", "https://chat18.aichatos8.com")
                .addParam(toMap)
                .post(true)
                .sync();
        return result;
    }

    /**
     * 构造访问参数
     * {
     *     "prompt": "springboot的配置文件",
     *     "userId": "#/chat/1721018362803",
     *     "network": true,
     *     "system": "",
     *     "withoutContext": false,
     *     "stream": false
     * }
    */
    private Map<String, Object> buildMap(ImRequest request) {
        RequestData requestData = new RequestData();
        requestData.setNetwork(true);
        requestData.setPrompt(request.getMessage());
        requestData.setUserId("#/chat/1721018362803");
        requestData.setWithoutContext(false);
        requestData.setStream(false);
        Map<String, Object> toMap = BeanUtil.beanToMap(requestData);
        return toMap;
    }

    // 请求数据的 JavaBean 类
    @Data
    class RequestData {
        private String prompt;
        private String userId;
        private boolean network;
        private String system;
        private boolean withoutContext;
        private boolean stream;
    }

}
